<template>
  <div name="patientManagement" class="patientManagement">
    <el-form :inline="true" :model="searchForm">
      <!--搜索框-->
      <el-form-item>
        <el-input
            v-model="searchForm.params.name"
            placeholder="名称"
            clearable>
        </el-input>
      </el-form-item>


      <el-form-item>
        <el-button @click="getPatientInfo">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible = true" >新增</el-button>
        <!--确认按钮-->
        <el-popconfirm title="确定要删除这些记录吗？"
                       @confirm="delHandle(null)"
                       style="margin-left: 10px;">
          <el-button type="danger"
                     slot="reference"
                     :disabled="delBtnStu">批量删除</el-button>
        </el-popconfirm>

      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        border
        stripe
        :data="patientListInfo"
        tooltip-effect="dark"
        style="width: 80%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="patientId"
          label="识别码"
          width="100">
      </el-table-column>

      <el-table-column
          prop="realName"
          label="姓名"
          width="100">
      </el-table-column>
      <el-table-column
          prop="birthday"
          label="年龄" width="75">
        <template slot-scope="scope">
          {{changeBirthday(scope.row.birthday)}}
        </template>
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别" width="75">
      </el-table-column>
      <el-table-column
          prop="height"
          label="身高(m)"
          width="75">
      </el-table-column>

      <el-table-column
          prop="weight"
          label="体重(kg)"
          width="85">
      </el-table-column>

      <el-table-column
          label="其他信息"
          width="100">
        <el-button
            slot-scope="scope"
            @click="showMoreInfo(scope.row)">
        查看
        </el-button>
      </el-table-column>

      <el-table-column
          width="150px"
          label="操作">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="editHandle(scope.row.patientId)"
          >编辑</el-button>

          <el-divider direction="vertical"></el-divider>

          <el-popconfirm title="确定要删除这条记录吗？"
                         @confirm="delHandle(scope.row.patientId)">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <!--其他信息弹出框-->
    <el-dialog :visible.sync="showMoreInfoDig">

      <el-descriptions
          title="更多信息"
          :column="1"
          border
          direction="vertical">

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            手术史
          </template>
          {{textChange(moreInfo.operationHistory)}}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            临床病史
          </template>
          {{textChange(moreInfo.clinicalHistory)}}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            过敏史
          </template>
          {{textChange(moreInfo.allergy)}}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

  <!--编辑弹窗-->
    <el-dialog title="患者信息"
               :visible.sync="dialogFormVisible"
               width="600px"
               @closed="resetForm('editForm')">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editForm">
        <el-form-item label="患者姓名" prop="realName" label-width="100px">
          <el-input v-model="editForm.realName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="birthday" label-width="100px">
          <el-date-picker style="width: 180px;"
                          v-model="editForm.birthday"
                          type="datetime"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          placeholder="出生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身高(m)" prop="height" label-width="100px">
          <el-input v-model="editForm.height" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="体重(kg)" prop="weight" label-width="100px">
          <el-input v-model="editForm.weight" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex" label-width="100px">

          <el-select v-model="editForm.sex" placeholder="请选择类型">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手术史" prop="operationHistory" label-width="100px">
          <el-input v-model="editForm.operationHistory" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="临床病史" prop="clinicalHistory" label-width="100px">
          <el-input v-model="editForm.clinicalHistory" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="过敏史" prop="allergy" label-width="100px">
          <el-input v-model="editForm.allergy" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="绑定账号" prop="userBind" label-width="100px">
          <el-input v-model="editForm.userBind" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click.native="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>




</template>

<script>
export default {
  name: "patientManagement",
  data(){
    let validateRealName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入患者姓名'))
      }
      let regex = /^[\u4E00-\u9FA5]+$/;
      if(!regex.test(value)){
        callback(new Error('非中文字符'));
      }

      callback();

    };

    let validateUserBind = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('绑定的用户账号'));
      }
      let regex = /^\d{6,}$/;
      if(!regex.test(value)){
        callback(new Error('非合法账号格式'));
      }
      callback();
    };

    let validateWeight = (rule, value, callback) => {
      if(value.toString() !== '') {
        let regex = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/;
        if (!regex.test(value)) {
          callback(new Error('非带小数点数字'));
        }

        if (value < 0.5 || value > 600.0)
          callback(new Error('非数据合法区间[0.5-600.0]'));
      }
      callback();
    };

    let validateHeight = (rule, value, callback) => {
      if(value.toString() !== '') {
        let regex = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/;
        if (!regex.test(value)) {
          callback(new Error('非带小数点数字'));
        }

        if (value < 0.5 || value > 3.0)
          callback(new Error('非数据合法区间[0.5-3.0]'));
      }
      callback();
    }

    return{
      //更多消息窗
      showMoreInfoDig: false,
      //删除键
      delBtnStu: true,
      //编辑窗
      dialogFormVisible: false,

      //搜索对象
      searchForm: {
        data: '',
        method: "all-page",
        params: {
          current: this.current,
          name: '',
          size: this.size
        }
      },
      //
      patientListInfo: [
        {
          patientId: 0,
          realName: '',
          birthday: 0,
          sex: '',
          height: 0.0,
          weight: 0.0,
          operationHistory: '',
          clinicalHistory: '',
          allergy: '',
          userBind: ''
        }
      ],
      moreInfo:{
        operationHistory: '',
        clinicalHistory: '',
        allergy: '',

      },


      //编辑窗口数据
      editForm: {
        patientId: 0,
        realName: '',
        birthday: 0,
        sex: '',
        height: '',
        weight: '',
        operationHistory: '',
        clinicalHistory: '',
        allergy: '',
        userBind: ''
      },

      editFormRules: {
        realName: [
          {required: true,validator: validateRealName , trigger: 'blur'}
        ],

        userBind: [
          {required: true,validator: validateUserBind , trigger: 'blur'}
        ],

        weight: [
            {required: false,validator: validateWeight, trigger: 'blur'}
        ],

        height: [
            {required: false,validator: validateHeight, trigger: 'blur'}
        ]
      },

      current: 1,
      total: 0,
      size: 10,

    }
  },
  created() {
    this.getPatientInfo();
  }
  ,methods: {
    getPatientInfo(){
      const self = this;
      let json = {
        method: this.searchForm.params.name
            ? 'name-page'
            : 'all-page' ,
        params: {
          name: this.searchForm.params.name ? this.searchForm.params.name : 'null',
          'current': self.current,
          'size': self.size
        }
      }

      self.$axios.post('api/patient/findPatientInfo',json)
          .then(res=>{
              self.patientListInfo = res.data.data.data;
              self.current = res.data.data.currentPage;
              self.size = res.data.data.size;
              self.total = res.data.data.total;
          })

    },

    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.patientId)
      })
      console.log(ids)
      let url = 'api/patient/deletePatientInfo'


      this.$axios.post(url, {'ids': ids}).then(res => {



        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getPatientInfo()
          }
        });
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    editHandle(id){
        console.log(id)
        let json = {
          patientId: id,
        }
        this.$axios.post("api/patient/selectPatientById",json).then(res => {
          this.editForm = res.data.data
          this.dialogFormVisible = true
        })

    },
    //换显示数
    handleSizeChange(val) {
      this.size = val
      this.getPatientInfo()
    },
    //换页
    handleCurrentChange(val) {
      this.current = val
      this.getPatientInfo()
    },
    //重置弹出表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.permDialogFormVisible = false
    },
    //提交编辑
    submitEditForm(formName){

      this.$refs[formName].validate((valid) => {
        console.log("edit")
        if (valid) {
          this.$axios.post('api/patient/' + (this.editForm.patientId
              ? "modifyPatientInfo"
              : "addPatientInfo") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getPatientInfo()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //将生日转为年龄
    changeBirthday(val){

      let date = val.toString().split("-");

      let year = Number(new Date().getFullYear());
      let month = Number(new Date().getMonth());


      let uYear = Number(date[0]);
      let uMonth = Number(date[1]);

      let display = uMonth > month
          ? year - uYear
          : year - uYear - 1;

      if(display === 0){
        display =  month - uMonth > 0
            ? month - uMonth + '个月'
            : '1个月';
      }

      return display;
    },

    showMoreInfo(val){
      const self = this;
      self.moreInfo.allergy = val.allergy;
      self.moreInfo.clinicalHistory = val.clinicalHistory;
      self.moreInfo.operationHistory = val.operationHistory;

      self.showMoreInfoDig = true;

    },
    textChange(val){
      if(val === null){
        return '暂无信息';
      }
      return val;
    }



  }
}
</script>

<style scoped>
  .patientManagement{
    margin: 15px 15px;
  }
  .el-pagination{
    margin: 0 auto; text-align: center;
    /*margin-top: 22px;*/
  }

</style>